import axios from 'axios'
import { stringify } from '@/utils/qs'
import config from '@/config'
import store from '@/store'
import errorHandler from '@/utils/errorHandler'

class ApiError extends Error {
  constructor(code, status, message) {
    super(message)
    this.code = code
    this.status = status
    this.message = message
  }
}

export default {
  install(Vue) {
    axios.interceptors.response.use(null, async error => {
      if (error.message.indexOf('Network Error') >= 0) {
        error = new ApiError('0000', 0, '网络错误，无法连接到服务器')
      } else if (error.response.data) {
        const { code, status, message } = error.response.data
        error = new ApiError(code, status, message)
      }
      errorHandler(error)
      return Promise.reject(error)
    })

    Object.assign(
      axios.defaults, 
      {
        baseURL: config.api.baseURL,
        paramsSerializer: params => stringify(params),
        transformRequest: [(data, headers) => {
          const { token } = store.state.auth
          headers['Content-Type'] = 'application/json'
          if (token) {
            headers['Authorization'] = `Bearer ${token}`
          }
          return JSON.stringify(data)
        }],
        transformResponse: [data => {
          return data ? JSON.parse(data) : null
        }],
      }
    )

    Vue.prototype.$isApiError = error => {
      return error instanceof ApiError
    }

    Vue.prototype.$axios = axios
  }
}
